<!-- eslint-disable no-irregular-whitespace -->
<template>
  <!-- 添加一个外层 div，设置 Flex 布局属性 -->
  <div class="radio-group-wrapper">
    <span>详情展示位置：</span>
    <a-radio-group v-model="position">
      <a-radio value="top">Top</a-radio>
      <a-radio value="right">Right</a-radio>
      <a-radio value="bottom">Bottom</a-radio>
      <a-radio value="left">Left</a-radio>
    </a-radio-group>
    <a-button
      type="primary"
      status="success"
      @click="loadData"
      style="bottom: 10px"
      >刷新 <IconRefresh
    /></a-button>
  </div>
  <!-- <div :style="{ marginTop: '20px' }">
    <a-button type="primary" @click="handleClick">Open Drawer</a-button>
  </div> -->
  <a-drawer
    :width="900"
    :height="900"
    :visible="visible"
    :placement="position"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> {{ questionDraw.title }} </template>
    <div>
      <span>题目内容：</span>
      <hr />
      <MdEditor :value="questionDraw.content" />
      <div style="margin-top: 15px"></div>
      <span>题目答案：</span>
      <hr />
      <MdEditor :value="questionDraw.answer" />
      <!-- 新增判题用例展示区域 -->
      <div style="margin-top: 15px"></div>
      <span>判题用例：</span>
      <hr />
      <div
        v-for="(item, index) in questionDraw.judgeCase"
        :key="index"
        style="margin-bottom: 10px"
      >
        <div><strong>输入:</strong> {{ item.input }}</div>
        <div><strong>输出:</strong> {{ item.output }}</div>
      </div>
    </div>
  </a-drawer>
  <div id="questionCheckView">
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.pageNum,
        total,
        pageSizeOptions: [10, 20, 50, 100],
      }"
      class="arco-table-cell"
    >
      <template #tags="{ record }">
        <a-space>
          <a-tag
            v-for="(tag, index) of parseTags(record.tags)"
            :key="index"
            color="green"
            >{{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #optional="{ record }">
        <div style="display: flex; gap: 8px">
          <a-button type="outline" @click="doDetail(record)">详情</a-button>
          <a-button @click="pass(record)" status="success">通过</a-button>
          <a-button @click="reject(record)" status="danger">拒绝</a-button>
        </div>
             
      </template>
         
    </a-table>
     
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { IconRefresh } from "@arco-design/web-vue/es/icon";
import {
  Page_Question_,
  Question,
  QuestionVO,
  QuestionControllerService,
} from "../../../generatedQue";
import message from "@arco-design/web-vue/es/message";
import MdEditor from "@/components/MdEditor.vue";
const tableRef = ref();
const visible = ref(false);
const position = ref("right");
const questionDraw = ref({
  title: "",
  content: "",
  answer: "",
});

const doDetail = async (record: QuestionVO) => {
  console.log(record.id);
  const id = record.id; // 直接使用 record.id，无需转换
  const res = await QuestionControllerService.getQuestionByIdUsingGet("", id);
  if (res.code === 0) {
    console.log(res.data);
    questionDraw.value.title = record.title;
    console.log(record);
    questionDraw.value.content = record.content;
    questionDraw.value.answer = res.data?.answer || "";
    // 解析 judgeCase 字符串为数组，如果解析失败则设为空数组
    try {
      questionDraw.value.judgeCase = JSON.parse(res.data?.judgeCase || "[]");
    } catch (error) {
      questionDraw.value.judgeCase = [];
    }
    visible.value = true;
  } else {
    message.error("加载失败，" + res.message);
  }
};
const pass = async (record: QuestionVO) => {
  await QuestionControllerService.checkQuestionUsingPost("", {
    id: record.id,
    pass: true,
  });

  loadData();
  message.success("审核成功");
};
const reject = async (record: QuestionVO) => {
  await QuestionControllerService.checkQuestionUsingPost("", {
    id: record.id,
    pass: false,
  });

  loadData();
  message.success("审核成功");
};
const handleOk = () => {
  visible.value = false;
};
const handleCancel = () => {
  visible.value = false;
};
/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const dataList = ref([] as Array<QuestionVO>);
const total = ref(0);
const searchParams = ref({
  pageSize: 10,
  pageNum: 1,
});
const loading = ref(true);
const loadData = async () => {
  const res = await QuestionControllerService.listQuestionCheckByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    dataList.value.forEach((item: QuestionVO) => {
      //将时间戳转换为格式YYYY-MM-DD HH:mm:ss
      if (item.createTime) {
        const date = new Date(item.createTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        item.createTime = `${year}-${month}-${day} ${hours}:${minutes}`;
      }
    });
    console.log(dataList.value);
    total.value = res.data.total;
    loading.value = false;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const columns = [
  // {
  //   title: "id",
  //   dataIndex: "id",
  // },
  {
    title: "标题",
    dataIndex: "title",
    align: "center",
  },
  // {
  //   title: "内容",
  //   dataIndex: "content",
  // },
  {
    title: "标签",
    slotName: "tags",
    align: "center",
  },
  // {
  //   title: "答案",
  //   dataIndex: "answer",
  // },
  // {
  //   title: "提交数",
  //   dataIndex: "submitNum",
  // },
  // {
  //   title: "通过数",
  //   dataIndex: "acceptedNum",
  // },
  {
    title: "限时",
    dataIndex: "judgeConfig.timeLimit",
    align: "center",
  },
  {
    title: "内存限制",
    dataIndex: "judgeConfig.memoryLimit",
    align: "center",
  },
  {
    title: "堆栈限制",
    dataIndex: "judgeConfig.stackLimit",
    align: "center",
  },
  // {
  //   title: "判题用例",
  //   dataIndex: "judgeCase",
  // },
  {
    title: "创建用户",
    dataIndex: "userVO.userName",
    align: "center",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    align: "center",
  },
  {
    title: "操作",
    slotName: "optional",
    align: "center",
  },
];
// 用来解析 tags 字符串的函数
// 修改后的 parseTags 方法
const parseTags = (tags: any): string[] => {
  if (!tags) {
    return [];
  }
  // 如果 tags 已经是数组，则直接返回
  if (Array.isArray(tags)) {
    return tags;
  }
  // 如果 tags 是字符串
  if (typeof tags === "string") {
    try {
      const parsed = JSON.parse(tags);
      // 确保解析结果是数组
      if (Array.isArray(parsed)) {
        return parsed;
      }
    } catch (error) {
      // JSON 解析失败，可能是普通的逗号分隔字符串
    }
    return tags.split(",");
  }
  // 如果 tags 既不是字符串也不是数组，就将其转换字符串后按逗号分割
  return String(tags).split(",");
};
</script>
<style>
#questionCheckView {
  max-width: 1400px;
  margin: 0 auto;
}
.arco-table-container {
  width: 1400px !important;
}
.radio-group-wrapper {
  display: flex;
  justify-content: center; /* 水平居中 */
}
</style>
